package com.crealth.handler;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.Config;
import com.crealth.ConstantDefine;
import com.crealth.Result.FollowupConsumerResult;
import com.crealth.crmserver.CRMServerHandler;
import com.crealth.crmserver.SessionManager;
import com.crealth.db.CdrDb;
import com.crealth.db.CompanyDb;
import com.crealth.db.ConsumerDb;
import com.crealth.db.ConsumerProductDb;
import com.crealth.db.MobileAttributionDb;
import com.crealth.db.MonthPlanDb;
import com.crealth.db.SupportedVoiceCodecsDb;
import com.crealth.db.TeamDb;
import com.crealth.db.UserDb;
import com.crealth.db.WeekPlanDb;
import com.crealth.job.HeartbeatJob;
import com.crealth.manager.SipAccountManager;
import com.crealth.memcached.ConsumerCached;
import com.crealth.memcached.UserCached;
import com.crealth.model.ConsumerInfoModel;
import com.crealth.model.MobileAttributionModel;
import com.crealth.model.MonthPlanModel;
import com.crealth.model.SupportedVoiceCodecsModel;
import com.crealth.model.TeamModel;
import com.crealth.model.UserModel;
import com.crealth.model.WeekPlanModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.StringUtil;
import com.crealth.utils.Utils;

public class UserHandler {
	private static Logger logger = Logger.getLogger("running_log");
	private static Logger errorLog = Logger.getLogger("error_log");
	//private static final Logger clientLog = Logger.getLogger("client_connect");
	private static String limitClientVersion = "";
	
	public static NetMessageData login(IoSession session, NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		String name = msgJson.getString("loginName");
		name = name.trim();
		String pwd = msgJson.getString("pwd");
		String version = "";
		if (msgJson.containsKey("version")) {
			version = msgJson.getString("version");
		}
		if (name.length() < 1 || pwd.length() < 3) {
			return null;
		}
		if (limitClientVersion == null || limitClientVersion.length() == 0) {
			limitClientVersion = UserDb.selectClientVersion();
		}
		if (Config.needLimitClientVersion > 0) {
			if (version.length() == 0 || 
					!Utils.compareVersion(limitClientVersion, version) ) {
				resJson.put("resCode", ErrorCode.ERROR_Limit_Client);
				sendMsg.setMsgBody(resJson.toJSONString());
				return sendMsg;
			}
		}
		int resCode = 0;
		UserModel userInfo = UserDb.selectUserByLoginName(name);
		if (userInfo == null) {
			resCode = ErrorCode.USER_NOT_EXIST;
			resJson.put("resCode", resCode);		
			sendMsg.setMsgBody(resJson.toJSONString());			
			return sendMsg;
		}
		if (userInfo.getForbidLogin() == 1) {
			resCode = ErrorCode.LONGIN_FORBID;
			resJson.put("resCode", resCode);		
			sendMsg.setMsgBody(resJson.toJSONString());			
			return sendMsg;
		}
		
		int userID = userInfo.getId();
		String loginName = userInfo.getLoginName();
		String longinPwd = userInfo.getLoginPwd();		
		logger.info("login: "+loginName+" userID: "+userID);
		int position = userInfo.getPosition();
		if ( (position == ConstantDefine.Sales_Man || 
			position == ConstantDefine.Group_Leader || 
			position == ConstantDefine.Customer_Service || 
			position == ConstantDefine.Team_Manager || 
			position == ConstantDefine.Installmenter ) 
			&& msgJson.containsKey("macAddr") ) {
			String loginMacAddr = msgJson.getString("macAddr");
			String userMac = userInfo.getMacAddr();
			if (userMac.length() == 0) {
				UserDb.updateUserMacAddr(userID, loginMacAddr);
			}
			if (userMac.length() > 0 && !userMac.equals(loginMacAddr)) {
				UserDb.updateUserLastLoginMacAddr(userID, loginMacAddr);
				resCode = ErrorCode.LONGIN_MAC_CHANGE;
				resJson.put("resCode", resCode);		
				sendMsg.setMsgBody(resJson.toJSONString());
				
				NetMessageData notiMsg = new NetMessageData();
				JSONObject notiJson = revData.getRevDataMsgJson();
				//int companyID = userInfo.getCompanyID();
				notiJson.put("resCode", 0);
				notiJson.put("loginUserID", userID);
				notiJson.put("loginUserName", userInfo.getUserName());
				notiMsg.setMsgBody(notiJson.toJSONString());
				notiMsg.setMsgCmd(NetMessageData.Net_REV_LOGIN_Noti);
				ResponseMsgQueue.sendCompanyTopMgr(userID, notiMsg);
				int companyID = userInfo.getBelongCompanyID();
				ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, notiMsg);
				
				return sendMsg;
			}
		}		
						
		if (!longinPwd.equals(pwd)) {
			resCode = ErrorCode.LOGIN_PWD_ERROR;
			resJson.put("resCode", resCode);		
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		UserCached.updateUserOnlineStatus(userID, true);
		int topCompanyID = CompanyDb.getTopCompanyID(userInfo.getCompanyID());
		SupportedVoiceCodecsModel voiceCodecs = SupportedVoiceCodecsDb.selectSupportedVoiceCodecs(topCompanyID);
		if (voiceCodecs != null) {
			voiceCodecs.toJSONObject(resJson);
		}
		SessionManager.addUserSession(userID, session);
		userInfo.toJSONObject(resJson);
		resJson.put("incomingSipIP", userInfo.getIncomingServerIP());
		resJson.put("sipIP", userInfo.getSipServerIP());
		int callSum = CdrDb.selectUserOnedayCallSum(userID);
		int holdSum = CdrDb.selectUserHoldCallSum(userID);
		int ringSum = CdrDb.selectUserRingCallSum(userID);
		int holdTimeSum = CdrDb.selectUserHoldTimeSum(userID);
		int gtOneminute = CdrDb.selectGreaterThanOneminute(userID);
		resJson.put("callSum", callSum);
		resJson.put("ringSum", ringSum);
		resJson.put("holdSum", holdSum);		
		resJson.put("holdTimeSum", holdTimeSum);
		resJson.put("gtOneminute", gtOneminute);
		resJson.put("resCode", resCode);
		if (userInfo.getPosition() == ConstantDefine.Sales_Man ||  
			userInfo.getPosition() == ConstantDefine.Group_Leader ||
			userInfo.getPosition() == ConstantDefine.Team_Manager ) {
			TeamModel team = TeamDb.selectTeamByID(userInfo.getTeamID());
			if (team != null) {
				resJson.put("teamInfo", team.toJSONObject());
			}
		}
		Integer showConsumerInfo = UserDb.selectIsShowConsumerInfo();
		if (showConsumerInfo != null) {
			resJson.put("showConsumerInfo", showConsumerInfo);
		}
		else {
			resJson.put("showConsumerInfo", 1);
		}
		sendMsg.setMsgBody(resJson.toJSONString());
		
		return sendMsg;
	}
	
	public static NetMessageData logOut(NetMessageData revData) {		
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			return null;
		}
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			return null;
		}
		String strSipAct = msgJson.getString("sipAct");
		if (strSipAct == null || strSipAct.length() == 0) {
			return null;
		}
		
		UserCached.updateUserOnlineStatus(userID, false);
		SessionManager.removeUserSessionByID(userID);
		
		return null;
	}
	
	public static NetMessageData reConnect(IoSession session, NetMessageData revData) {		
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			return null;
		}
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			return null;
		}
		SessionManager.addUserSession(userID, session);
		
		return null;
	}
	
	public static NetMessageData addStaff(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel opUser = UserCached.selectUserByID(userID);
		int resCode = 0;
		UserModel addUserObj = new UserModel();
		addUserObj.parseFromJson(msgJson);
		String name = addUserObj.getUserName().trim();
		if (name == null || name.length() < 1) {
			errorLog.error("----  addStaff name is null  ----");
			return null;
		}
		UserModel existUser = UserDb.selectUserByName(name);
		if (existUser != null) {
			resCode = ErrorCode.ERROR_SAMENAME_EXIST;
			resJson.put("resCode", resCode);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		// 分公司不能新增按揭部经理
		if ( (!opUser.isTopCompany() || opUser.getPosition() < ConstantDefine.Head_Manager)
			&& addUserObj.getPosition() == ConstantDefine.InstallDpmMGR ) {
			resCode = ErrorCode.ERROR_Limited_Auth;
			resJson.put("resCode", resCode);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		String strPwd = "123456";  //StringUtil.getRandomString(6);
		addUserObj.setLoginPwd(strPwd);
		int teamID = addUserObj.getTeamID();
		if (teamID > 0 ) {
			TeamModel team = TeamDb.selectTeamByID(teamID);
			if (addUserObj.getPosition() == ConstantDefine.Sales_Man || 
				addUserObj.getPosition() == ConstantDefine.Group_Leader	) {				
				if (team != null) {
					addUserObj.setLeaderID(team.getTeamLeader());
				}
			}
		}

		UserDb.insertStaff(addUserObj);
		int addUserID = addUserObj.getId();
		if (addUserID > 0) {
			SipAccountManager.distributeSipActToUser(addUserID);
			if (addUserObj.getPosition() == ConstantDefine.Team_Manager) {
				TeamDb.updateTeamLeaderByTeamID(teamID, addUserID);
				UserDb.updateTeamUserLeaderByTeamID(teamID, addUserID);
			}
			WeekPlanModel weekPlan = new WeekPlanModel();
			weekPlan.setUserID(addUserID);
			WeekPlanDb.insertWeekPlan(weekPlan);
			MonthPlanModel monthPlan = new MonthPlanModel();
			monthPlan.setUserID(addUserID);
			MonthPlanDb.insertMonthPlan(monthPlan);
		}
		UserCached.updateUserMOB(addUserObj);
		
		resJson.put("opUser", userID);
		resJson.put("resCode", resCode);
		resJson.put("userInfo", addUserObj.toJSONObject(null));
		sendMsg.setMsgBody(resJson.toJSONString());
		
		NetMessageData notiMsg = new NetMessageData();
		notiMsg.setMsgBody(resJson.toJSONString());
		notiMsg.setMsgCmd(NetMessageData.Net_Add_Staff_Noti);
		int companyID = addUserObj.getBelongCompanyID();
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, notiMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, notiMsg);
		ResponseMsgQueue.sendMsgToCustomerService(userID, companyID, notiMsg);
		ResponseMsgQueue.sendMsgToAdministration(userID, companyID, notiMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, companyID, notiMsg);
		if (addUserObj.getLeaderID() > 0) {
			ResponseMsgQueue.addMsgToQueue(NetMessageData.Net_Add_Staff_Noti, addUserObj.getLeaderID(), notiMsg);
		}
		
		return sendMsg;
	}
	
	public static NetMessageData obtainLeaders(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			return null;
		}		
		//int userID = msgJson.getIntValue("id");
		List<UserModel> cliModels = UserDb.selectSalesManager();
		int num = cliModels.size();
		int realNum = 0;
		if (num > 0) {
			JSONArray jsonArray = new JSONArray();
			for (UserModel info : cliModels) {
				if (info.getStaffStatus() != 6) {
					realNum++;
					jsonArray.add(info.toJSONObject(null));
				}				
			}
			resJson.put("leaders", jsonArray.toJSONString());
		}				
		resJson.put("cnt", realNum);		
		sendMsg.setMsgBody(resJson.toJSONString());
		
		return sendMsg;
	}
	
	public static NetMessageData obtainUnderlings(NetMessageData revData) {
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			return null;
		}		
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		int userPos = user.getPosition();
		List<UserModel> underlings = null;
		if (userPos >= ConstantDefine.Head_Manager || 
				userPos == ConstantDefine.Administration || 
				userPos == ConstantDefine.Installmenter || 
				userPos == ConstantDefine.InstallDpmMGR || 
				userPos == ConstantDefine.Financer || 
				userPos == ConstantDefine.Customer_Service ) {
			underlings = UserDb.selectAllUser();
		}
		else {
			underlings = UserDb.selectUnderling(userID);			
		}
		int num = 0;
		if (underlings != null) {
			num = underlings.size();
		}				
		if (num == 0) {
			NetMessageData sendMsg = new NetMessageData();
			JSONObject resJson = new JSONObject();
			resJson.put("cnt", num);		
			sendMsg.setMsgBody(resJson.toJSONString());			
			return sendMsg;
		}
		
		List<FollowupConsumerResult> waitApprovalls = 
				ConsumerProductDb.selectWaitApprovalNum();
		Map<Integer, Integer> waitApprovalMap = new HashMap<Integer, Integer>();
		for (FollowupConsumerResult curWait : waitApprovalls) {
			waitApprovalMap.put(curWait.getUserID(), curWait.getWaitApprovalNum());
		}
		
		JSONArray jsonArray = new JSONArray();
		for (int idx = 0; idx < underlings.size(); ++idx) {
			UserModel info = underlings.get(idx);
			int curUserID = info.getId();
			JSONObject curUserInfoJson = info.toJSONObject(null);
			if (waitApprovalMap.containsKey(curUserID)) {
				int curWaitNum = waitApprovalMap.get(curUserID);
				curUserInfoJson.put("waitApprovalNum", curWaitNum);
			}
			if (user.getPosition() >= ConstantDefine.Branch_Mgr_Fu) {
				if (info.getPosition() < ConstantDefine.Branch_Mgr_Fu) {
					String macAddr = info.getMacAddr();
					String preLoginMac = info.getPreLoginMac();
					if (preLoginMac.length() > 0 && !preLoginMac.equals(macAddr)) {
						curUserInfoJson.put("changePC", 1);
					}
				}
			}
			jsonArray.add(curUserInfoJson);
			if (jsonArray.size() == 20 || idx == underlings.size()-1) {
				NetMessageData sendMsg = new NetMessageData();
				JSONObject resJson = new JSONObject();
				resJson.put("underling", jsonArray);
				resJson.put("cnt", num);
				resJson.put("index", idx);
				sendMsg.setMsgBody(resJson.toJSONString());
				ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), userID, sendMsg);
				jsonArray = new JSONArray();
			}
		}
		
		return null;
	}
	
	public static NetMessageData obtainLastestVersion(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		String version = UserDb.selectClientVersion();
		resJson.put("lastestVersion", version);
		sendMsg.setMsgBody(resJson.toJSONString());
		
		return sendMsg;
	}
	
	public static NetMessageData modifyPwd(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		String newPwd = msgJson.getString("newPwd");
		if (newPwd == null || newPwd.length() < 6) {
			return null;
		}
		UserCached.updateUserLoginPwd(userID, newPwd);
		int resCode = 0;		
		resJson.put("resCode", resCode);
		sendMsg.setMsgBody(resJson.toJSONString());
		
		return sendMsg;
	}
	
	public static NetMessageData onHeartBeat(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserCached.updateUserOnlineStatus(userID, true);
		long curTm = System.currentTimeMillis() / 1000;
		HeartbeatJob.heartbeatMap.put(userID, curTm);
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData forceCloseAllClient(NetMessageData revData) {
		JSONObject msgJson = revData.getRevDataMsgJson();
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		int operPos = user.getPosition();		
		
		resJson.put("msg", "force close client");
		if (operPos > ConstantDefine.Branch_Mgr) {			
			CRMServerHandler.sendMsgToClients(resJson.toJSONString(), 
					NetMessageData.Net_Stop_All);
			return null;
		} else {
			sendMsg.setMsgCmd(NetMessageData.Net_Stop_All);
			sendMsg.setMsgBody(resJson.toJSONString());
			
			int companyID = user.getBelongCompanyID();
			ResponseMsgQueue.sendMsgToCompany(userID, companyID, sendMsg);
			return sendMsg;
		}
		
	}
	
	public static NetMessageData sendXiBaoBroadcast(NetMessageData revData) {
		JSONObject msgJson = revData.getRevDataMsgJson();
		String xbContent = msgJson.getString("xbContent");
		if (xbContent.length() < 3) {
			return null;
		}
		
		JSONObject resJson = new JSONObject();
		resJson.put("xbContent", xbContent);
		CRMServerHandler.sendMsgToClients(resJson.toJSONString(), 
				NetMessageData.Net_XiBao_Noti);
		
		return null;
		
	}
	
	
	public static NetMessageData hideAllClientConsumerInfo() {
		JSONObject resJson = new JSONObject();
		int isHide = UserDb.selectIsShowConsumerInfo();
		int setValue = 0;
		if (isHide == 0) {
			setValue = 1;
		}
		Integer res = UserDb.updateIsShowConsumerInfo(setValue);
		if (res != null) {
			resJson.put("resCode", 0);
			resJson.put("setValue", setValue);
			Config.showSearchConsumerInfo = setValue;
			CRMServerHandler.sendMsgToClients(resJson.toJSONString(), 
				NetMessageData.Net_HIDE_CONSUMER_INFO);
		}
		
		return null;
	}
	
	public static NetMessageData commitMobileAttribute(NetMessageData revData) {
		//NetMessageData sendMsg = new NetMessageData();
		//JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			return null;
		}
		String mobile = "" + msgJson.getInteger("mobile");
		if (mobile == null || mobile.length() != 7) {
			return null;
		}
		if (MobileAttributionDb.selectMobileExist(mobile) != null) {
			return null;
		}
		String city = msgJson.getString("city");
		String province = msgJson.getString("province");
		String supplier = msgJson.getString("supplier");
		MobileAttributionModel mobileModel = new MobileAttributionModel();
		mobileModel.setCity(city);
		mobileModel.setMobile(mobile);
		mobileModel.setProvince(province);
		mobileModel.setSupplier(supplier);
		MobileAttributionDb.insertMobileAttribution(mobileModel);
		//sendMsg.setMsgBody(resJson.toJSONString());
		return null;
	}
	
	public static NetMessageData uploadRecordFile(NetMessageData revData) {		
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			errorLog.error("uploadRecordFile msgJson is null");
			return null;
		}
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			errorLog.error("uploadRecordFile userID is 0");
			return null;
		}
		String dtype = msgJson.getString("dtype");
		String data = msgJson.getString("data");
		String fileName = msgJson.getString("fileName");		
		String fileDir;
		String osName = Utils.getOSName();
		String strMonth = StringUtil.getCurrentDay().substring(0, 6);
		if (osName.startsWith("Window")) {
			Utils.checkAndCreateDir("./record/");
			fileDir = "./record/" + strMonth;
			Utils.checkAndCreateDir(fileDir);
		}
		else {
			fileDir = "/datadisk/webhost/record/" + strMonth;
			Utils.checkAndCreateDir(fileDir);			
			File f = new File(fileDir);
	        f.setWritable(true, false);				
		}
		Utils.saveUploadFile(userID, dtype, data, 
				fileName, fileName, fileDir);
		
		int resCode = 0;		
		resJson.put("resCode", resCode);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData modifyStaffInfo(NetMessageData revData) {		
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		int staffID = msgJson.getIntValue("userID");
		UserModel oldStaffInfo = UserCached.selectUserByID(staffID);
		UserModel user = new UserModel();
		user.parseFromJson(msgJson);
		int teamID = user.getTeamID();
		if (teamID > 0) {
			if (user.getPosition() == ConstantDefine.Team_Manager) {
				int teamLeaderID = user.getId();
				TeamDb.updateTeamLeaderByTeamID(teamID, teamLeaderID);
				UserDb.updateTeamUserLeaderByTeamID(teamID, teamLeaderID);				
			}
			TeamModel team = TeamDb.selectTeamByID(teamID);
			if (team != null && (user.getPosition() == ConstantDefine.Sales_Man || 
					user.getPosition() == ConstantDefine.Group_Leader) ) {
				user.setLeaderID(team.getTeamLeader());
			}
		}
		
		//  离职
		if (user.getStaffStatus() == 6) {
			int leaderID = user.getLeaderID();
			if (user.getPosition() == ConstantDefine.Team_Manager) {
				leaderID = 0;
			} else {
				if (leaderID == 0) {
					if (oldStaffInfo != null) {
						leaderID = oldStaffInfo.getLeaderID();
					}
				}
			}
			ConsumerCached.updateConsumerUserLeaveOffice(staffID, leaderID);
			UserDb.updateSipAccountByID(staffID, "", "", "", 
					"", "", "");
			resJson.put("consumerTargetID", leaderID);
			resJson.put("consumerFromID", staffID);
		} else {			
			if (oldStaffInfo != null && (oldStaffInfo.getSipAccount() == null || 
					oldStaffInfo.getSipAccount().trim().length() == 0) ) {
				SipAccountManager.distributeSipActToUser(staffID);
			}
		}
		UserCached.updateUserByUserID(user);
		UserCached.updateUserMOB(user);
		
		resJson.put("opUser", userID);
		resJson.put("resCode", 0);
		resJson.put("userInfo", user.toJSONObject(null));
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, 0, sendMsg);
		
		int companyID = user.getBelongCompanyID();		
		ResponseMsgQueue.sendMsgToCustomerService(userID, companyID, sendMsg);
		ResponseMsgQueue.sendMsgToAdministration(userID, companyID, sendMsg);
		
		JSONArray jsonArray = new JSONArray();
		if (oldStaffInfo.getTeamID() != user.getTeamID() ||   
			oldStaffInfo.getBelongCompanyID() != user.getBelongCompanyID() 	) {
			List<Integer> consumerIDls = ConsumerDb.selectConsumerIDByUserID(staffID);
			for (Integer cmrID : consumerIDls) {
				ConsumerInfoModel consumer = ConsumerCached.selectConsumer(cmrID);
				if (consumer != null) {
					jsonArray.add(consumer.toJSONObject());
				}
			}
		}
		
		// 换了团队   之前的团队经理  需要删掉
		if (oldStaffInfo.getTeamID() != user.getTeamID()) {			
			if (oldStaffInfo.getLeaderID() > 0) {
				NetMessageData sendMsg2 = new NetMessageData();
				JSONObject resJson2 = new JSONObject();
				resJson2.put("opUser", userID);
				resJson2.put("resCode", 0);
				resJson2.put("delUser", staffID);
				sendMsg2.setMsgBody(resJson2.toJSONString());
				sendMsg2.setMsgCmd(revData.getMsgCmd());
				ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), oldStaffInfo.getLeaderID(), sendMsg2);
			}
			if (user.getLeaderID() > 0) {
				NetMessageData sendMsg3 = new NetMessageData();
				JSONObject resJson3 = new JSONObject();
				resJson3.put("opUser", userID);
				resJson3.put("resCode", 0);
				resJson3.put("userInfo", user.toJSONObject(null));
				resJson3.put("consumerInfoArr", jsonArray);
				sendMsg3.setMsgBody(resJson3.toJSONString());
				sendMsg3.setMsgCmd(revData.getMsgCmd());				
				ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), user.getLeaderID(), sendMsg3);
			}
		} else {
			if (user.getLeaderID() > 0) {
				ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), user.getLeaderID(), sendMsg);
			}
		}
		
		int oldCompanyID = oldStaffInfo.getBelongCompanyID();
		// 换公司了
		if (oldCompanyID != companyID ) {			
			NetMessageData sendMsg4 = new NetMessageData();
			JSONObject resJson4 = new JSONObject();
			resJson4.put("opUser", userID);
			resJson4.put("resCode", 0);
			resJson4.put("delUser", staffID);
			sendMsg4.setMsgBody(resJson4.toJSONString());
			sendMsg4.setMsgCmd(revData.getMsgCmd());
			ResponseMsgQueue.sendBranchCompanyMgr(userID, oldCompanyID, sendMsg4);
			
			NetMessageData sendMsg5 = new NetMessageData();
			JSONObject resJson5 = new JSONObject();
			resJson5.put("opUser", userID);
			resJson5.put("resCode", 0);
			resJson5.put("userInfo", user.toJSONObject(null));
			resJson5.put("consumerInfoArr", jsonArray);
			sendMsg5.setMsgBody(resJson5.toJSONString());
			sendMsg5.setMsgCmd(revData.getMsgCmd());				
			ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg5);
		} else {		
			ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);		
		}
		
		return sendMsg;
	}
	
	public static NetMessageData resetVoiceCodecs(NetMessageData revData) {			
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user == null || user.getPosition() != ConstantDefine.Admin_Manager) {
			return null;
		}
		
		SupportedVoiceCodecsModel voiceCodecs = new SupportedVoiceCodecsModel();
		voiceCodecs.parseFromJson(msgJson);
		Integer res = SupportedVoiceCodecsDb.updateSupportedVoiceCodecs(voiceCodecs);
		if (res != null && res > 0) {			
			voiceCodecs.toJSONObject(resJson);
			CRMServerHandler.sendMsgToClients(resJson.toJSONString(), 
					NetMessageData.Net_RS_VOICECODECS);
		}		
		
		return null;
	}
	
	public static NetMessageData resetUserPwd(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		//int userID = msgJson.getIntValue("id");
		/*
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Branch_Company_Mgr
			&& user.getPosition() != ConstantDefine.Customer_Service ) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}*/	
		String newPwd = "123456";
		int setUserID = msgJson.getIntValue("setUserID");
		UserCached.updateUserLoginPwd(setUserID, newPwd);
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());		
		return sendMsg;
	}
	
	public static NetMessageData confirmPwd(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject msgJson = revData.getRevDataMsgJson();
		JSONObject resJson = new JSONObject();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserDb.selectUserByID(userID);
		String strPwd = msgJson.getString("pwd");
		if (user == null || !user.getLoginPwd().equals(strPwd)) {
			resJson.put("resCode", ErrorCode.LOGIN_PWD_ERROR);
		} else {
			resJson.put("resCode", 0);
		}		
		
		sendMsg.setMsgBody(resJson.toJSONString());		
		return sendMsg;
	}
	
	//  同意  更改 MAC
	public static NetMessageData agreeChangePC(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject msgJson = revData.getRevDataMsgJson();
		JSONObject resJson = new JSONObject();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Branch_Mgr_Fu) {
			int resCode = ErrorCode.ERROR_Limited_Auth;
			resJson.put("resCode", resCode);		
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		int agreeUserID = msgJson.getIntValue("agreeUserID");
		Integer res = UserDb.updateUserLoginMacAddrToMac(agreeUserID);
		if (res == null || res == 0) {
			return null;
		}
		resJson.put("resCode", 0);
		resJson.put("opUser", userID);
		resJson.put("agreeUserID", agreeUserID);
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		UserModel salesMan = UserCached.selectUserByID(agreeUserID);
		if (salesMan != null) {
			int companyID = salesMan.getBelongCompanyID();
			ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		}
		
		return sendMsg;
	}
	
	//  上传入职文件
	public static NetMessageData uploadEntryFile(NetMessageData revData) {		
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();		
		int opUserID = msgJson.getIntValue("id");		
		String dtype = msgJson.getString("dtype");
		String data = msgJson.getString("data");
		String srcFileName = msgJson.getString("fileName");		
		String fileDir;
		String osName = Utils.getOSName();
		if (osName.startsWith("Window")) {
			fileDir = "./staff_file/";
		}
		else {
			fileDir = "/datadisk/webhost/staff_file/";			
		}
		String saveName = "" + opUserID + "_" + System.currentTimeMillis() + "." + Utils.getFileSuffix(srcFileName);
		boolean saveRes = Utils.saveUploadFile(opUserID, dtype, data, 
				srcFileName, saveName, fileDir);
		if (saveRes) {
			int fileUse = msgJson.getIntValue("fileUse");
			int staffID = msgJson.getIntValue("staffID");
			if (1 == fileUse) {
				UserDb.updateEntryFile(staffID, srcFileName, saveName);
			} else if (2 == fileUse) {
				UserDb.updatePictureFile(staffID, srcFileName, saveName);
			} else if (3 == fileUse) {
				UserDb.updateIdentityFile(staffID, srcFileName, saveName);
			} else if (4 == fileUse) {
				UserDb.updateBankFile(staffID, srcFileName, saveName);
			} else if (5 == fileUse) {
				UserDb.updateOtherFile(staffID, srcFileName, saveName);
			}
			
			resJson.put("resCode", 0);
			resJson.put("fileUse", fileUse);
			resJson.put("staffID", staffID);
			resJson.put("fileName", srcFileName);
			resJson.put("fileUrl", saveName);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		return null;
	}
	
}
